<?php
namespace app\admin\controller;

use app\common\model\AdminMenu;
use app\common\model\AdminRole;
use utils\Result;

class Menu extends Common
{
    public function index()
    {
        $this->AuthCheck();
        $list = AdminMenu::order('sort asc')->all();

        $this->assign('list',$this->menulist($list));

        return $this->view->fetch();
    }

    /**
     * 新增菜单
     * @return string|Result
     * @throws \Exception
     */
    public function add()
    {
        $this->AuthCheck();

        if ($this->request->isPost()){

            $param = $this->request->param();

            $insert = (new AdminMenu())->allowField(true)->save($param);

            if (config('app_debug')){
                $list = AdminMenu::all();
                $result = [];
                foreach ($list as $v){
                    $result[] = $v['id'];
                }
                AdminRole::where('id',1)->update(['limit_array' => implode(',',$result)]);
            }

            if ($insert) return Result::success('添加成功');

            return Result::error('添加成功');
        }
        $menu = AdminMenu::order('create_time desc')->all();

        $menu = $this->menulist($menu);

        $this->assign(compact('menu'));

        return $this->view->fetch();
    }

    /**
     * 编辑菜单
     * @return string|Result
     * @throws \think\Exception\DbException
     */
    public function edit()
    {
        $this->AuthCheck();

        $model = new AdminMenu();

        if ($this->request->isPost()){

            $param = $this->request->post('data');

            $id = $this->request->post('id');

            $update = $model->allowField(true)->save($param,['id' => $id ]);

            if ($update) return Result::success('更新成功');

            return Result::error('更新失败');
        }

        $info = $model->get($this->request->get('id'));

        $menu = $model->order('create_time desc')->all();

        $menu = $this->menulist($menu);

        $this->assign(compact('menu','info'));

        return $this->view->fetch();
    }
    public function del()
    {
        $this->AuthCheck();
        $id = $this->request->get('id');

        $del = AdminMenu::destroy($id);

        if ($del) return Result::success('删除成功');

        return Result::error('删除失败');

    }
    /**
     * 字体图标设置
     * @return string
     * @throws \Exception
     */
    public function font()
    {
        return $this->view->fetch();
    }
}